const db = require('../../mongoDB')
const requestIp = require('request-ip')
const crypto = require('crypto');
const axios = require('axios')
const { auth,ckconfig } = require('./auth')


exports.init = async (ctx) => {
  let navtops, friendlinks, tagArr, titleO, title, tags,icps,icp,page,pageSize,user,push
  Promise.all([
    navtops = await db.navtops.find({}).sort({"sort":1}),
    friendlinks = await db.friendlinks.find(),
    tagArr = await db.tags.find(),
    titleO = await db.titles.findOne({ path: '/' }),
    icps = await db.icps.findOne({ _id: '5c514bfefc3ec336487cf232' }),
    page = await db.page.findOne({ _id: '5c35a29b2af4d7b7766c5b72' }),
    user = await db.user.findOne({ _id: '5c6ccd9cfc3ec37fd8195292' })
    
  ]).then(() => {
    title = titleO.title
    icp = icps.icp
    tags = []
    pageSize = page.pageSize
    push = user.push
    for (let i = 0; i < tagArr.length; i++) {
      let tmp = {}
      tmp.name = tagArr[i].name
      tmp.type = i % 5
      tmp.path = tagArr[i].path
      tags.push(tmp)
    }
    ctx.body = { title, tags, navtops, friendlinks, icp, pageSize, push }
  })
}
exports.list = async (ctx) => {
  let param = {
    "type": "$type",
    "title": "$title",
    "date": "$date",
    "tags": "$tags",
    "browse": "$browse",
    "brief": "$brief"
  };
  let tags = await db.tags.findOne({ name: ctx.query.type })
  let query = tags?{tags:ctx.query.type}:(ctx.query.type?{type:ctx.query.type}:{})
  let page = ctx.query.page ? ctx.query.page : 1
  let pageSize = await db.page.findOne({ _id: '5c35a29b2af4d7b7766c5b72' });
  let result = await db.contents.find(query, param).limit(pageSize.pageSize).skip((page - 1) * pageSize.pageSize).sort({ date: -1 });
  let total = await db.contents.countDocuments(query);
  ctx.body = { result, total ,pageSize:pageSize.pageSize }
}
exports.content = async (ctx) => {
  let content = await db.contents.findOne({ _id: ctx.query.id })
  content.browse = content.browse + 1
  content.save()
  ctx.body = content
}
exports.verCode = async function(ctx) {
  console.log(ctx.request.body);
  let name = ctx.request.body.name
  let user = await db.user.findOne({ name })
  if (!user) {
    ctx.body = {
      code: 401,
      message:'用户名不存在！'
    }
    return
  }
  let time = new Date().getTime()
  if (time-user.time < 1000*60*5) {
    ctx.body = {
      code: 401,
      message:`验证码已发送，有效期剩余：${Math.floor(300-(time - user.time)/1000)}秒`
    }
    return
  }
  let ip = requestIp.getClientIp(ctx.request); 
  let md5 = crypto.createHash('md5');
  let md5Str = md5.update(`${time}:${name}`).digest('hex');
  let verCode = md5Str.slice(0,8)
  user.verCode = verCode
  user.time = time
  user.ip = ip
  user.token = md5Str
  user.save()

  let url = encodeURI(`${user.push}?text=登录验证&desp= - 登录验证码:${verCode} \n - 5分钟内有效`)
  axios.get(url)
  console.log(`用户 ${name} 验证码推送成功: 当前验证码为 ${verCode}`);
  ctx.body = { code: 200, verCode }
}
exports.login = async function(ctx) {
  const name = ctx.request.body.user
  const verCode = ctx.request.body.verCode
  let user = await db.user.findOne({ name })
  if (!user) {
    ctx.body = { code: 401, message: '用户名输入有误，请检查后重新输入！' }
    return
  }
  if (verCode == user.verCode) {
    ctx.cookies.set('user',user.name,ckconfig)
    ctx.cookies.set('token',user.token,ckconfig)
    ctx.body = { code: 200,token:user.token }
  } else {
    ctx.body = { code: 401,message:'验证吗有误,请重新输入！' }
  }
}
exports.listCount = async function (ctx) {
  if (await auth(ctx)) {
    let page = await db.page.findOne({ _id: '5c35a29b2af4d7b7766c5b72' })
    let pageSize = ctx.request.body.pageSize
    page.pageSize = pageSize
    page.save()
    ctx.body = { code: 200,message:'修改成功' }
  }
}
exports.title = async function (ctx) {
  if (await auth(ctx)) {
    let title = await db.titles.findOne({ path: '/' })
    let setTitle = ctx.request.body.title
    title.title = setTitle
    title.save()
    ctx.body = { code: 200,message:'修改成功' }
  }
}
exports.icp = async function (ctx) {
  if (await auth(ctx)) {
    let icp = await db.icps.findOne({ _id: '5c514bfefc3ec336487cf232' })
    let setICP = ctx.request.body.icp
    icp.icp = setICP
    icp.save()
    ctx.body = { code: 200,message:'修改成功' }
  }
}
exports.push = async function (ctx) {
  if (await auth(ctx)) {
    let cookieUser = ctx.cookies.get('user')
    let user = await db.user.findOne({ name: cookieUser })
    let setPush = ctx.request.body.push
    user.push = setPush
    user.save()
    ctx.body = { code: 200,message:'修改成功' }
  }
}
exports.navTops = async function (ctx) {
  if (await auth(ctx)) {
    let navTop = await db.navtops.findOne({ _id: ctx.request.body._id })
    navTop.name = ctx.request.body.name
    navTop.link = ctx.request.body.link
    navTop.sort = ctx.request.body.sort
    navTop.save()
    ctx.body = { code: 200,message:'修改成功' }
  }
}
